//
//  EditPatronDetailViewController.m
//  CS Inventory Manager
//
//  Created by Billy Zoellers on 3/7/13.
//  Copyright (c) 2013 Transylvania University. All rights reserved.
//

#import "EditPatronDetailViewController.h"
#import "PatronDetailViewController.h"
#import "PatronViewController.h"
#import "AppDelegate.h"

@interface EditPatronDetailViewController ()

@end

@implementation EditPatronDetailViewController
@synthesize thePatron,inLast,inFirst,inEmail,inPass,inType,inActive,inPhone,delegate;

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super init];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (IBAction)saveButton:(id)sender {
    //Error checking: make sure all fields are filled in
    if ((inLast.text.length != 0)&&(inFirst.text.length != 0)&&(inEmail.text.length != 0)&&(inPhone.text.length != 0)) {
        // set all params for URL
        NSString *uid = [NSString stringWithFormat:@"%d",[thePatron patronId]];
        NSString *type;
        NSString *active;
        // get type
        if (inType.selectedSegmentIndex == 0) {
            // stu
            type = @"1";
        } else {
            // fac
            type = @"2";
        }
        
        // get isActive?
        if (inActive.on == YES) {
            active = @"Y";
        } else {
            active = @"N";
        }
        
        // generate the URL and use %20 encoding
        NSString *urlStr = [NSString stringWithFormat:@"http://www.cs.transy.edu/zoellers/inventory/patron.php?secret=pass&id=%@&last=%@&first=%@&email=%@&type=%@&tel=%@&active=%@",uid,inLast.text,inFirst.text,inEmail.text,type,inPhone.text,active];
        NSString *final = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        
        NSLog(@"The url is: >>>>>%@<<<<<", final);
        
        NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:final]];
        
        // make web request and catch error
        NSError * e;
        NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:&e];
        
        // log the value returned from the web server
        NSString *value = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        NSLog(@"return from web: %@", value);
        
        if ([uid isEqualToString:@"0"]) {
            // this was a new item, get the ID back
            int newID = [[[value componentsSeparatedByString:@"*"] objectAtIndex:1] integerValue];
            NSLog(@"Got back from web: %i", newID);
            [thePatron setPatronId:newID];
        }
        
        // also add the data locally
        [thePatron setLastName:inLast.text];
        [thePatron setFirstName:inFirst.text];
        [thePatron setEmail:inEmail.text];
        [thePatron setTelephone:inPhone.text];
        [thePatron setActive:inActive.on];
        
        if ([type isEqual:@"1"]) {
            [thePatron setPatronType:@"Student"];
        } else {
            [thePatron setPatronType:@"Faculty"];
        }
        
        // reload the tables to show whatever changes were made
        if ([delegate isKindOfClass:[PatronDetailViewController class]]) {
            // this means we're doing an edit, so we need to push two reloads!
            [[self.delegate tableView] reloadData];
            [[[self.delegate delegate] tableView] reloadData];
            
        } else {
            // grab the AppDelegate
            AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
            
            // add the patron the array AFTER we have created it
            [appDelegate.patrons addObject:thePatron];
            
            // we're adding, so the delegate is the IVC and we only reload the IVC
            [[self.delegate tableView] reloadData];
            
        }
        
        [self dismissViewControllerAnimated:YES completion:nil];
    }
}

- (IBAction)cancelButton:(id)sender {
    
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - Text Field Delegate
- (BOOL)textFieldShouldReturn:(UITextField *)theTextField {
    if (theTextField == inLast) {
        [inFirst becomeFirstResponder];
    } else if (theTextField == inFirst) {
        [inEmail becomeFirstResponder];
    } else if (theTextField == inEmail) {
        [inPhone becomeFirstResponder];
    }else if (theTextField == inPhone) {
        [inPhone resignFirstResponder];
    }
    
    return YES;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    NSLog(@"%@",[thePatron lastName]);
    inLast.text = [thePatron lastName];
    inFirst.text = [thePatron firstName];
    inEmail.text = [thePatron email];
    inPhone.text = [thePatron telephone];
    
    // allocate the segmented control
    inType = [[UISegmentedControl alloc] initWithFrame:CGRectMake(100, 10, 185, 30)];
    [inType insertSegmentWithTitle:@"Student" atIndex:0 animated:YES];
    [inType insertSegmentWithTitle:@"Faculty" atIndex:1 animated:YES];
    if ([[thePatron patronType] isEqual: @"Student"]) {
        inType.selectedSegmentIndex = 0;
        
    } else if ([[thePatron patronType] isEqual: @"Faculty"]) {
        inType.selectedSegmentIndex = 1;
    }

    
    // allocate the switch
    inActive = [[UISwitch alloc] initWithFrame:CGRectMake(100, 10, 185, 30)];
    if ([thePatron active]) {
        [inActive setOn:YES];
    } else {
        [inActive setOn:NO];
    }
    
    // set title - THIS IS NOT WORKING, NEED TO LOOK BACK AT THIS
    // * the if works fine, the setTitle does not * //
    if ([delegate isKindOfClass:[PatronDetailViewController class]]) {
        // this means we're doing an edit, so want the title to be the persons name
        NSMutableString *title = [[NSMutableString alloc] init];
        [title appendString:@"Edit - "];
        [title appendString:[thePatron lastName]];
        [title appendString:@", "];
        [title appendString:[thePatron firstName]];
        [self setTitle:title];
    } else {
        // doing an add, so make it something generic
        self.title = @"Add Patron";
    }
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{

    return 6;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"editPatronCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
    cell.detailTextLabel.text = @"";
    
    // make a text field
    UITextField *inputTextField = [[UITextField alloc] initWithFrame:CGRectMake(85, 10, 530, 30)];
    inputTextField.adjustsFontSizeToFitWidth = YES;
    inputTextField.textColor = [UIColor blackColor];
    inputTextField.backgroundColor = [UIColor clearColor];
    inputTextField.autocorrectionType = UITextAutocorrectionTypeNo; // no auto correction support
    inputTextField.autocapitalizationType = UITextAutocapitalizationTypeNone; // no auto capitalization support
    inputTextField.tag = 0;
    inputTextField.clearButtonMode = UITextFieldViewModeAlways;
    [inputTextField setEnabled: YES];
    inputTextField.delegate = self;
    
    // Configure the cell...
    switch ([indexPath row]) {
        case 0:
            cell.textLabel.text = @"Last Name";
            inputTextField.text = [[self thePatron] lastName];
            inputTextField.keyboardType = UIKeyboardTypeDefault;
            inputTextField.returnKeyType = UIReturnKeyNext;
            inputTextField.autocapitalizationType = UITextAutocapitalizationTypeWords;
            self.inLast = inputTextField;
            [cell.contentView addSubview:inputTextField];
            inputTextField = nil;
            break;
        case 1:
            cell.textLabel.text = @"First Name";
            inputTextField.text = [[self thePatron] firstName];
            inputTextField.keyboardType = UIKeyboardTypeDefault;
            inputTextField.returnKeyType = UIReturnKeyNext;
            inputTextField.autocapitalizationType = UITextAutocapitalizationTypeWords;
            self.inFirst = inputTextField;
            [cell.contentView addSubview:inputTextField];
            inputTextField = nil;
            break;
        case 2:
            cell.textLabel.text = @"Email";
            inputTextField.text = [thePatron email];
            inputTextField.keyboardType = UIKeyboardTypeEmailAddress;
            inputTextField.returnKeyType = UIReturnKeyNext;
            self.inEmail = inputTextField;
            [cell.contentView addSubview:inputTextField];
            inputTextField = nil;
            break;
        case 3:
            cell.textLabel.text = @"Phone";
            inputTextField.text = [thePatron telephone];
            inputTextField.keyboardType = UIKeyboardTypeNumberPad;
            inputTextField.returnKeyType = UIReturnKeyNext;
            self.inPhone = inputTextField;
            [cell.contentView addSubview:inputTextField];
            inputTextField = nil;
            break;
        case 4:
            cell.textLabel.text = @"Type";

            [cell.contentView addSubview:inType];
            break;
        case 5:
            cell.textLabel.text = @"Active";
            [cell.contentView addSubview:inActive];
            break;
    }
    
    
    return cell;
}

@end
